import { defineStore } from 'pinia'
import { ref, reactive } from 'vue'
import type { TablePaginationConfig } from 'ant-design-vue'
import { 
  getRoleList, 
  getRoleDetail,
  createRole,
  updateRole,
  deleteRole,
  getRolePermissions,
  saveRolePermissions,
  changeRoleStatus
} from '@/api/system/role'
import type { 
  Role,
  RoleQuery,
  CreateRole,
  UpdateRole,
  RolePermissionTreeNode
} from '@/types/api/system/role'
import { message } from 'ant-design-vue'
import { useI18n } from 'vue-i18n'

/**
 * 角色管理Store
 */
export const useRoleStore = defineStore('role', () => {
  const { t } = useI18n()
  
  // ------------ 加载状态 ------------
  const loading = ref(false)
  const submitLoading = ref(false)
  const permissionLoading = ref(false)
  
  // ------------ 数据列表 ------------
  const roleList = ref<Role[]>([])
  const total = ref(0)
  
  // ------------ 查询参数 ------------
  const queryParams = reactive<RoleQuery>({
    keyword: '',
    status: undefined,
    page: 1,
    pageSize: 10,
    dateRange: undefined
  })
  
  // ------------ 弹窗状态 ------------
  const formModalVisible = ref(false)
  const permissionModalVisible = ref(false)
  
  // ------------ 表单状态 ------------
  const currentRoleId = ref('')
  const permissionTree = ref<RolePermissionTreeNode[]>([])
  const checkedKeys = ref<string[]>([])
  
  const formData = reactive({
    roleName: '',
    roleCode: '',
    roleSort: 0,
    status: 1,
    remark: ''
  })
  
  // ------------ 分页配置 ------------
  const pagination = reactive<TablePaginationConfig>({
    current: 1,
    pageSize: 10,
    total: 0,
    showTotal: (total: number) => `共 ${total} 条`,
    showSizeChanger: true,
    showQuickJumper: true
  })
  
  // ------------ 数据操作方法 ------------
  // 获取角色列表
  const fetchRoleList = async (params: RoleQuery) => {
    loading.value = true
    try {
      const { data, success, message: msg } = await getRoleList(params)
      if (success) {
        roleList.value = data.list
        total.value = data.total
        pagination.total = data.total
      } else {
        message.error(msg || t('common.fetchFailed'))
      }
    } catch (error) {
      message.error(t('common.fetchFailed'))
    } finally {
      loading.value = false
    }
  }
  
  // 获取角色详情
  const fetchRoleDetail = async (id: string) => {
    try {
      const { data, success, message } = await getRoleDetail(id)
      if (success && data) {
        // 更新表单数据
        Object.assign(formData, {
          roleName: data.roleName,
          roleCode: data.roleCode,
          roleSort: data.roleSort,
          status: data.status,
          remark: data.remark
        })
        return data
      } else {
        throw new Error(message || '获取角色详情失败')
      }
    } catch (error) {
      throw error
    }
  }
  
  // 提交表单
  const submitForm = async () => {
    submitLoading.value = true
    try {
      let result
      if (!currentRoleId.value) {
        // 新增
        const params: CreateRole = {
          roleName: formData.roleName,
          roleCode: formData.roleCode,
          roleSort: formData.roleSort,
          status: formData.status,
          remark: formData.remark
        }
        result = await createRole(params)
      } else {
        // 编辑
        const params: UpdateRole = {
          roleName: formData.roleName,
          roleCode: formData.roleCode,
          roleSort: formData.roleSort,
          status: formData.status,
          remark: formData.remark
        }
        result = await updateRole(currentRoleId.value, params)
      }
      
      if (result.success) {
        message.success(currentRoleId.value ? t('common.updateSuccess') : t('common.createSuccess'))
        formModalVisible.value = false
        await fetchRoleList(queryParams)
        return true
      } else {
        message.error(result.message || t('common.operationFailed'))
        return false
      }
    } catch (error) {
      message.error(t('common.operationFailed'))
      return false
    } finally {
      submitLoading.value = false
    }
  }
  
  // 删除角色
  const removeRoles = async (ids: string[]) => {
    try {
      const result = await deleteRole(ids)
      if (result.success) {
        message.success(ids.length > 1 ? t('common.batchDeleteSuccess') : t('common.deleteSuccess'))
        // 如果当前页数据都被删除且不是第一页，则跳转到上一页
        if (ids.length >= roleList.value.length && pagination.current && pagination.current > 1) {
          pagination.current -= 1
        }
        await fetchRoleList(queryParams)
        return true
      } else {
        message.error(result.message || t('common.deleteFailed'))
        return false
      }
    } catch (error) {
      message.error(t('common.deleteFailed'))
      return false
    }
  }
  
  // 修改角色状态
  const changeStatus = async (id: string, status: number) => {
    try {
      // 找到当前角色并标记加载状态
      const role = roleList.value.find(item => item.id === id)
      if (role) {
        role.statusLoading = true
      }
      
      const result = await changeRoleStatus(id, status)
      if (result.success) {
        message.success(t('common.statusChangeSuccess'))
        // 更新角色列表中的状态
        if (role) {
          role.status = status
        }
        return true
      } else {
        message.error(result.message || t('common.statusChangeFailed'))
        // 恢复原状态
        if (role) {
          role.status = status === 1 ? 0 : 1
        }
        return false
      }
    } catch (error) {
      message.error(t('common.statusChangeFailed'))
      // 恢复原状态
      const role = roleList.value.find(item => item.id === id)
      if (role) {
        role.status = status === 1 ? 0 : 1
      }
      return false
    } finally {
      // 取消加载状态
      const role = roleList.value.find(item => item.id === id)
      if (role) {
        role.statusLoading = false
      }
    }
  }
  
  // 获取角色权限
  const fetchRolePermissions = async (id: string) => {
    loading.value = true
    try {
      const { data, success, message } = await getRolePermissions(id)
      if (success && data) {
        if (!data.permissionTree || data.permissionTree.length === 0) {
          throw new Error('权限树数据为空')
        }
        permissionTree.value = data.permissionTree
        checkedKeys.value = data.checkedKeys
        return data
      } else {
        throw new Error(message || '获取角色权限失败')
      }
    } catch (error) {
      throw error
    } finally {
      loading.value = false
    }
  }
  
  // 将选中的节点转换为扁平的权限ID列表
  const getCheckedPermissions = () => {
    if (!permissionTree.value || permissionTree.value.length === 0) {
      return []
    }
    
    // 获取所有选中的节点ID
    return checkedKeys.value
  }
  
  // 保存角色权限
  const savePermissions = async (id: string) => {
    loading.value = true
    try {
      const permissions = getCheckedPermissions()
      const { success, message } = await saveRolePermissions(id, permissions)
      if (!success) {
        throw new Error(message || '保存权限失败')
      }
      return { success, message }
    } catch (error) {
      throw error
    } finally {
      loading.value = false
    }
  }
  
  // ------------ 状态操作方法 ------------
  // 打开表单弹窗
  const openFormModal = async (id?: string) => {
    resetForm()
    if (id) {
      currentRoleId.value = id
      await fetchRoleDetail(id)
    }
    formModalVisible.value = true
  }
  
  // 处理权限树选中变化
  const handlePermissionCheck = (keys: string[]) => {
    checkedKeys.value = keys
  }
  
  // 重置表单
  const resetForm = () => {
    Object.assign(formData, {
      roleName: '',
      roleCode: '',
      roleSort: 0,
      status: 1,
      remark: ''
    })
    currentRoleId.value = ''
  }
  
  // 重置查询参数
  const resetQuery = () => {
    Object.assign(queryParams, {
      keyword: '',
      status: undefined,
      dateRange: undefined,
      page: 1,
      pageSize: 10
    })
    pagination.current = 1
  }
  
  // 处理分页变化
  const handlePageChange = (page: number, pageSize?: number) => {
    pagination.current = page
    if (pageSize) {
      pagination.pageSize = pageSize
    }
    // 重新获取数据
    fetchRoleList({
      ...queryParams,
      page: pagination.current || 1,
      pageSize: pagination.pageSize || 10
    })
  }

  return {
    // 状态
    loading,
    submitLoading,
    permissionLoading,
    formModalVisible,
    permissionModalVisible,
    roleList,
    total,
    pagination,
    queryParams,
    formData,
    currentRoleId,
    permissionTree,
    checkedKeys,
    
    // 方法
    fetchRoleList,
    fetchRoleDetail,
    submitForm,
    removeRoles,
    changeStatus,
    fetchRolePermissions,
    savePermissions,
    openFormModal,
    resetForm,
    resetQuery,
    handlePageChange,
    handlePermissionCheck
  }
}) 